package org.netty.push.client;

import java.util.concurrent.TimeUnit;

import org.netty.push.core.proto.BaseMessage;
import org.netty.push.core.proto.PingRequestMsg;
import org.netty.push.core.proto.handler.MessageHandlerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ClientHandler extends SimpleChannelInboundHandler<BaseMessage>{
	Logger logger=LoggerFactory.getLogger(ClientHandler.class);
	
	private MessageHandlerManager messageHandlerManager;
	
	public ClientHandler(MessageHandlerManager messageHandlerManager) {
		this.messageHandlerManager=messageHandlerManager;
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, BaseMessage msg) throws Exception {
		  messageHandlerManager.handle(ctx, msg);
	}

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    	if(evt instanceof IdleStateEvent ) {
    		IdleStateEvent idleStateEvent=(IdleStateEvent)evt;
    		if(IdleState.WRITER_IDLE ==idleStateEvent.state()) {
    			System.err.println("ping....... ");
    			ctx.writeAndFlush(new PingRequestMsg());
    		}
    	}else {
            ctx.fireUserEventTriggered(evt);
    	}

    }
    
    @Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.debug(" 使用过程中断线重连");
		
		final EventLoop eventLoop = ctx.channel().eventLoop();
		eventLoop.schedule(new Runnable() {
			@Override
			public void run() {
				PushClient pushClient = new PushClient();
				pushClient.connected();
			}
		}, 5L, TimeUnit.SECONDS);
		super.channelInactive(ctx);
	}

}
